package com.bird.system.application.permission

import cn.dev33.satoken.stp.StpInterface
import cn.dev33.satoken.stp.StpUtil
import com.bird.component.cache.util.DataFetcher
import com.bird.component.lang.common.jackson.toKtData
import com.bird.component.lang.util.isnull
import com.bird.component.lang.util.saltMd5
import com.bird.component.security.common.SessionKey
import com.bird.system.application.auth.AuthAppGateway
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.stereotype.Component

/**
 * 权限接口实现
 */
@Component
class StpInterfaceImpl(
    private val authAppGateway: AuthAppGateway,
    private val objectMapper: ObjectMapper,
    private val roleMenuRepository: RoleMenuRepository,
):StpInterface {
    /**
     * 返回指定loginId所拥有的权限码集合
     */
    override fun getPermissionList(loginId: Any, loginType: String): List<String> {
        val userId = loginId as? Long
        if (userId.isnull()) {
            return emptyList()
        }
        return DataFetcher.fetcher<List<String>>()
            .fromCache {
                // 从缓存中获取权限码
               StpUtil.getSessionByLoginId(loginId)?.get(SessionKey.PERMISSION).toKtData(objectMapper)
            }.fromDb {
                roleMenuRepository.getPermListByRoleId(getRoleList(loginId, loginType).map { it.toLong() })
            }.saveToCache {
                // 保存权限码到缓存
                StpUtil.getSessionByLoginId(loginId)?.set(SessionKey.PERMISSION, it)
            }.ifNullDefault {
                // 如果为空返回默认值
                emptyList()
            }.fetch()?: emptyList()

    }
    /**
     * 返回指定loginId所拥有的角色标识集合
     */
    override fun getRoleList(loginId: Any?, loginType: String?): List<String> {
        val userId = (loginId as String).toLong()
        if (userId.isnull()) {
            return emptyList()
        }
        return DataFetcher.fetcher<List<String>>()
            .fromCache {
                // 从缓存中获取角色标识
                StpUtil.getSessionByLoginId(loginId)?.get(SessionKey.ROLE).toKtData(objectMapper)
            }.fromDb {
                //从数据库中获取
                authAppGateway.oneUser(userId!!)?.roles?.map { it.toString() } ?: emptyList()
            }.saveToCache {
                // 保存角色标识到缓存
                StpUtil.getSessionByLoginId(loginId)?.set(SessionKey.ROLE, it)
            }.ifNullDefault {
                // 如果为空返回默认值
                emptyList()
            }.fetch()?: emptyList()
    }
}

fun main() {
    println("123456".saltMd5("123456"))
}